package com.cykj.consumer;

import com.cykj.entity.CyOrderDO;
import com.cykj.feign.GoodControllerFeign;
import com.cykj.mapper.OrderMapper;
import com.cykj.mqEvent.CancelOrderEvent;
import com.cykj.vo.CyGoodVO;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author 王宇
 * @CreateTime: 2025-08-03  01:22
 * @BelongsProject: jd_seckill
 * @BelongsPackage: com.cykj.consumer
 * @description 取消订单的消费者监听
 */
@Component
@RocketMQMessageListener(topic = "cancel-order", consumerGroup = "${rocketmq.consumer.group}")
public class CancelOrderConsumer implements RocketMQListener<CancelOrderEvent> {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GoodControllerFeign goodControllerFeign;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onMessage(CancelOrderEvent cancelOrderEvent) {
        // 获取订单信息
        CyOrderDO order = orderMapper.getOrderById(cancelOrderEvent.getOrderId());

        // 如果订单超时未支付
        if (order.getPayState() == 0) {
            System.out.println("订单未支付，取消订单");
            // redis回滚库存
            redisTemplate.opsForValue().increment("stock:" + order.getGoodId(), order.getBuyCount());

            // 更新订单的超时状态为1
            orderMapper.updateOrderTimeOut(order.getId());
        } else {  // 订单已经支付
            // 修改数据库中的商品库存
            CyGoodVO cyGoodVO = new CyGoodVO();
            cyGoodVO.setGoodId(order.getGoodId());
            cyGoodVO.setCount(order.getBuyCount());
            goodControllerFeign.subGoodStock(cyGoodVO);
        }
    }
}
